package org.example.controller;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

@RestController
@RequestMapping("/api/images")
public class ImageController {

    @GetMapping("/example")
    public ResponseEntity<byte[]> getExampleImage() {
        try {
            // 从Classpath中读取图片文件
            Resource resource = new ClassPathResource("static/girl.jpg");
            // 将文件读取为字节数组
            byte[] imageBytes = Files.readAllBytes(resource.getFile().toPath());
            // 返回字节数组和合适的HTTP头部
            return ResponseEntity.ok()
                    .contentType(MediaType.IMAGE_JPEG)
                    .body(imageBytes);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/example2")
    public byte[] getExampleImage2() {
        try {
            // 从Classpath中读取图片文件
            Resource resource = new ClassPathResource("static/girl.jpg");
            // 将文件读取为字节数组
            byte[] imageBytes = Files.readAllBytes(resource.getFile().toPath());
            // 返回字节数组和合适的HTTP头部
            return imageBytes;
        } catch (IOException e) {
            e.printStackTrace();
            return new byte[10];
        }
    }
}
